首先,創建一個基本的 HTML 結構:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To-Do List</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>To-Do List</h1>
        <input type="text" id="taskInput" placeholder="Add a new task">
        <button id="addTaskButton">Add Task</button>
        <ul id="taskList"></ul>
    </div>
    <script src="script.js"></script>
</body>
</html>
接著,添加一些基本的樣式:
/* styles.css */
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.container {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    width: 300px;
}
input[type="text"] {
    width: calc(100% - 22px);
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 3px;
}
button {
    padding: 10px;
    background-color: #28a745;
    border: none;
    color: #fff;
    border-radius: 3px;
    cursor: pointer;
}
button:hover {
    background-color: #218838;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    padding: 10px;
    border-bottom: 1px solid #ddd;
}
li:last-child {
    border-bottom: none;
}
.deleteButton {
    margin-left: 10px;
    background-color: #dc3545;
    border: none;
    color: #fff;
    border-radius: 3px;
    cursor: pointer;
}
.deleteButton:hover {
    background-color: #c82333;
}
最後,實現基本的功能:
// script.js
document.addEventListener('DOMContentLoaded', () => {
    const taskInput = document.getElementById('taskInput');
    const addTaskButton = document.getElementById('addTaskButton');
    const taskList = document.getElementById('taskList');
    addTaskButton.addEventListener('click', () => {
        const taskText = taskInput.value.trim();
        if (taskText !== '') {
            const li = document.createElement('li');
            li.textContent = taskText;
            // Add a delete button to each task
            const deleteButton = document.createElement('button');
            deleteButton.textContent = 'Delete';
            deleteButton.className = 'deleteButton';
            deleteButton.addEventListener('click', () => {
                taskList.removeChild(li);
            });
            li.appendChild(deleteButton);
            taskList.appendChild(li);
            taskInput.value = '';
        }
    });
    // Allow pressing Enter to add tasks
    taskInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            addTaskButton.click();
        }
    });
});
這樣,你就有了一個基本的 To-Do List 應用程序。可以進一步擴展功能,比如儲存任務到本地,進行儲存、編輯任務等。